/**
 * 
 */
package com.zxc.mongodb;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.bson.BsonArray;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.zxc.jdbc.JdbcDemo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

/**
 * @author Administrator
 *
 */
public class MongodbDemo {

	public static void main(String[] args) {
		// 获取链接    
        MongoClient mongoClient = new MongoClient("192.168.100.10", 27017);   
        
        // 获取数据库    
        MongoDatabase database = mongoClient.getDatabase("base_info");    
        // 进入某个文档集    
        MongoCollection<Document> collection = database.getCollection("airports");    
        
        MongoCollection<Document> collection1 = database.getCollection("airport_error");    
        
        // 原始抓取
        // 日期
//        String s = "QWERTYUIOPASDFGHJKLZXCVBNM";
//        String s1 = "QWERTYUIOPASDFGHJKLZXCVBNM";
//        for (int i = 0; i < s.length(); i++) {
//        	for (int j = 0; j < s1.length(); j++) {
//				for (int j2 = 0; j2 < s1.length(); j2++) {
//					String code = ""+s.charAt(i)+s1.charAt(j)+s1.charAt(j2);
//					try {
//						String result = HttpUtil.get("https://flights.ctrip.com/international/search/api/poi/search?key="+code);
////				        System.out.println("code="+code+","+result);
//				        if(JSONUtil.isTypeJSON(result)) {
//				        	JSONObject json = JSONObject.parseObject(result);
//					        JSONArray data = json.getJSONArray("Data");
//					        if(CollectionUtil.isNotEmpty(data)) {
//					        	List<Object> jjj = data.stream().filter(e->{
//					        		JSONObject o = (JSONObject) e;
//					        		return StringUtils.equals(code, o.getString("Code"));
//					        	}).collect(Collectors.toList());
//					        	if(CollectionUtil.isNotEmpty(jjj)) {
//					        		Document doc = new Document();
//					        		doc.append("Code", code).append("data", JSONUtil.toJsonStr(jjj));
//					        		collection.insertOne(doc);
//					        	}
//					        }
//					        try {
//					        	int dd = RandomUtil.randomInt(1, 6);
//								Thread.sleep(dd*1000);
//							} catch (InterruptedException e) {
//							}
//				        }
//					} catch (Exception e) {
//						collection1.insertOne(new Document("Code",code).append("e", ExceptionUtil.stacktraceToString(e)));
//					}
//				}
//			}
//		}
        
        // 抓取失败的重新抓取
//        MongoCollection<Document> collection2 = database.getCollection("airport_error1"); 
//        collection1.find().map(d->{return d.getString("Code");}).forEach(new Block<String>() {
//
//			@Override
//			public void apply(String code) {
//	        	try {
//					String result = HttpUtil.get("https://flights.ctrip.com/international/search/api/poi/search?key="+code);
//					System.out.println(result);
//			        if(JSONUtil.isTypeJSON(result)) {
//			        	JSONObject json = JSONObject.parseObject(result);
//				        JSONArray data = json.getJSONArray("Data");
//				        if(CollectionUtil.isNotEmpty(data)) {
//				        	List<Object> jjj = data.stream().filter(e->{
//				        		JSONObject o = (JSONObject) e;
//				        		return StringUtils.equals(code, o.getString("Code"));
//				        	}).collect(Collectors.toList());
//				        	if(CollectionUtil.isNotEmpty(jjj)) {
//				        		System.out.println(JSONUtil.toJsonStr(jjj));
//				        		Document doc = new Document();
//				        		doc.append("Code", code).append("data", JSONUtil.toJsonStr(jjj));
//				        		collection.insertOne(doc);
//				        	}
//				        }
//			        }
//				} catch (Exception e) {
//					collection2.insertOne(new Document("Code",code).append("e", ExceptionUtil.stacktraceToString(e)));
//				}
//	        	
//	        	try {
//		        	int dd = RandomUtil.randomInt(1, 6);
//					Thread.sleep(dd*1000);
//				} catch (InterruptedException e) {
//				}
//			}
//		});
        
        // 分离出城市信息和机场信息
//        Map<String, Document> cityInfos = new HashMap<String, Document>();
//        
//        Map<String, Document> airportInfos = new HashMap<String, Document>();
//        collection.find().forEach(new Block<Document>() {
//
//			@Override
//			public void apply(Document doc) {
//	        	JSONArray arr = JSONArray.parseArray(doc.getString("data"));
//	        	for (Object o : arr) {
//					JSONObject j = (JSONObject) o;
//					if(j.getIntValue("Type") == 5) {// 城市
//						
//						Document city_doc = new Document();
//						for (Entry<String, Object> entry : j.entrySet()) {
//							city_doc.append("City_"+entry.getKey(), entry.getValue());
//						}
//						cityInfos.put(j.getString("Code"), city_doc);
//						
//						JSONArray cityDatas = j.getJSONArray("Datas");
//						if(CollectionUtil.isNotEmpty(cityDatas)) {
//							for (Object o1 : cityDatas) {
//								JSONObject j1 = (JSONObject) o1;
//								if(j1.getIntValue("Type") == 3) {
//									Document airport_doc = new Document(city_doc);
//									for (Entry<String, Object> entry : j1.entrySet()) {
//										airport_doc.append("Airport_"+entry.getKey(), entry.getValue());
//									}
//									airportInfos.put(j1.getString("Code"), airport_doc);
//								}
//							}
//						}
//						
//					}else if(j.getIntValue("Type") == 3) {
//						
//						Document airport_doc = new Document();
//						for (Entry<String, Object> entry : j.entrySet()) {
//							airport_doc.append("Airport_"+entry.getKey(), entry.getValue());
//						}
//						airportInfos.put(j.getString("Code"), airport_doc);
//						
//						
//						JSONArray cityDatas = j.getJSONArray("Datas");
//						if(CollectionUtil.isNotEmpty(cityDatas)) {
//							for (Object o1 : cityDatas) {
//								JSONObject j1 = (JSONObject) o1;
//								if(j1.getIntValue("Type") == 5) {
//									Document city_doc = new Document();
//									for (Entry<String, Object> entry : j1.entrySet()) {
//										city_doc.append("City_"+entry.getKey(), entry.getValue());
//									}
//									cityInfos.put(j1.getString("Code"), city_doc);
//									
//									airport_doc.putAll(city_doc);
//								}
//							}
//						}
//						
//					}
//	        	}
//			}
//		});
//        
//        MongoCollection<Document> collection3 = database.getCollection("airport_info");
//        collection3.insertMany(new ArrayList<Document>(airportInfos.values()));
//        
//        MongoCollection<Document> collection4 = database.getCollection("city_info");
//        collection4.insertMany(new ArrayList<Document>(cityInfos.values()));
        
        
     // 分离出只有城市信息
//      Map<String, Document> cityInfos = new HashMap<String, Document>();
//      collection.find().forEach(new Block<Document>() {
//
//			@Override
//			public void apply(Document doc) {
//	        	JSONArray arr = JSONArray.parseArray(doc.getString("data"));
//	        	for (Object o : arr) {
//					JSONObject j = (JSONObject) o;
//					if(j.getIntValue("Type") == 4) {// 城市
//						
//						Document city_doc = new Document();
//						for (Entry<String, Object> entry : j.entrySet()) {
//							city_doc.append("City_"+entry.getKey(), entry.getValue());
//						}
//						cityInfos.put(j.getString("Code"), city_doc);
//					}
//	        	}
//			}
//		});
//      MongoCollection<Document> collection4 = database.getCollection("city_info");
//      collection4.insertMany(new ArrayList<Document>(cityInfos.values()));
        
        // 指定城市代码的
//        List<Document> airportTmps = new ArrayList<Document>();
//        MongoCollection<Document> collection5 = database.getCollection("city_info");
//        collection5.find(Filters.in("City_Code", "DHU","VKG","ZHA")).forEach(new Block<Document>() {
//
//			@Override
//			public void apply(Document t) {
//				Document doc = new Document(t);
//				doc.remove("_id");
//				doc.append("Airport_EName", doc.get("City_EName"));
//				doc.append("Airport_CityName", doc.get("City_Name"));
//				doc.append("Airport_Code", doc.get("City_Code"));
//				doc.append("Airport_Province", doc.get("City_Province"));
//				doc.append("Airport_Spell", doc.get("City_Spell"));
//				doc.append("Airport_Name", doc.get("City_Name"));
//				doc.append("Airport_ShortSpell", doc.get("City_ShortSpell"));
//				doc.append("Airport_TimeZone", doc.get("City_TimeZone"));
//				doc.append("Airport_Type", 3);
//				doc.append("Airport_SuperShortName", doc.get("City_SuperShortName"));
//				doc.append("Airport_CityId", doc.get("City_CityId"));
//				doc.append("Airport_Country", doc.get("City_Country"));
//				doc.append("Airport_CountryCode", doc.get("City_CountryCode"));
//				airportTmps.add(doc);
//			}
//		});
//        MongoCollection<Document> collection6 = database.getCollection("airport_info");
//        collection6.insertMany(airportTmps);
        
        // 保存机场信息
        List<Map<String, Object>> errorList = new ArrayList<Map<String,Object>>();
//        MongoCollection<Document> collection7 = database.getCollection("airport_info");
//        collection7.find().forEach(new Block<Document>() {
//
//			@Override
//			public void apply(Document t) {
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("airport_code", t.get("Airport_Code"));
//				map.put("airport_ename", t.get("Airport_EName"));
//				map.put("airport_spell", t.get("Airport_Spell"));
//				map.put("airport_name", t.get("Airport_Name"));
//				map.put("airport_shortspell", t.get("Airport_ShortSpell"));
//				map.put("airport_timezone", t.get("Airport_TimeZone"));
//				map.put("airport_supershortname", t.get("Airport_SuperShortName"));
//				map.put("city_code", t.get("City_Code"));
//				map.put("city_ename", t.get("City_EName"));
//				map.put("city_name", t.get("City_Name"));
//				map.put("city_spell", t.get("City_Spell"));
//				map.put("city_shortspell", t.get("City_ShortSpell"));
//				map.put("city_province", t.get("City_Province"));
//				map.put("city_countrycode", t.get("City_CountryCode"));
//				map.put("city_country", t.get("City_Country"));
//				try {
//					JdbcDemo.insertAirports(map);
//				} catch (SQLException | InterruptedException e) {
//					e.printStackTrace();
//					errorList.add(map);
//				}
//			}
//		});
        
        // 保存城市信息
//      MongoCollection<Document> collection8 = database.getCollection("city_info");
//      collection8.find(Filters.eq("City_Type", 4)).forEach(new Block<Document>() {
//
//			@Override
//			public void apply(Document t) {
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("airport_code", t.get("City_Code"));
//				map.put("airport_ename", t.get("City_EName"));
//				map.put("airport_spell", t.get("City_Spell"));
//				map.put("airport_name", t.get("City_Name"));
//				map.put("airport_shortspell", t.get("City_ShortSpell"));
//				map.put("airport_timezone", t.get("Airport_TimeZone"));
//				map.put("airport_supershortname", t.get("Airport_SuperShortName"));
//				map.put("city_code", t.get("City_Code"));
//				map.put("city_ename", t.get("City_EName"));
//				map.put("city_name", t.get("City_Name"));
//				map.put("city_spell", t.get("City_Spell"));
//				map.put("city_shortspell", t.get("City_ShortSpell"));
//				map.put("city_province", t.get("City_Province"));
//				map.put("city_countrycode", t.get("City_CountryCode"));
//				map.put("city_country", t.get("City_Country"));
//				try {
//					JdbcDemo.insertAirports(map);
//				} catch (SQLException | InterruptedException e) {
//					e.printStackTrace();
//					errorList.add(map);
//				}
//			}
//		});
//        
//        System.out.println(JSONUtil.toJsonStr(errorList));
        /********************** 数据插入 ****************************/    
        // 创建新文档    
//         Document doc = new Document("name", "MongoDB")    
//         .append("type", "database").append("count", 1)    
//         .append("info", new Document("x", 203).append("y", 102));    
////         将文档插入文档集合    
//         collection.insertOne(doc);    

        // 创建一个包含多个文档的列表    
//         List<Document> documents = new ArrayList<Document>();    
//         for (int i = 0; i < 500000; i++) {   
//			TaskPoolUtil.pushGdsLogTask(new Runnable() {
//				
//				@Override
//				public void run() {
//					
//					try {
//						Document doc = new Document("name", "{\"routecodes\":\"SHE-CAN,CAN-BKK,BKK-PVG,PVG-SHE;CZ,CZ,MU,FM;CZ6301,CZ363,MU548,FM9367;2017-09-29 08:20:00/2017-09-29 12:20:00,2017-09-29 16:05:00/2017-09-29 17:55:00,2017-10-14 02:30:00/2017-10-14 07:10:00,2017-10-14 08:50:00/2017-10-14 11:25:00;B,B,S,B\",\"dsid\":\"ABUS_F-25\",\"travelInfo\":{\"dsid\":\"ABUS_F-25\",\"flightClass\":\"Economy\",\"adjustprice\":0,\"ds\":\"ABUS_F\",\"flightClassCode\":\"E\",\"priceInfo\":[{\"baseFare\":4710,\"baggage\":\"0,1-1P;2,3-2P\",\"firmAmountCid\":6,\"lastRmbFare\":3978,\"rebateAmount\":0,\"firmAmountHx\":0,\"fareExchangeRate\":0.8433,\"afterRebateFare\":3972,\"rebateExchangeRate\":1,\"passengerTypeName\":\"ADT\",\"rmbTax\":860.17,\"serviceFeeRate\":1,\"rmbFare\":3971.95,\"segmentPrice\":0,\"priceProfitCidId\":\"4\",\"rebateCurrency\":\"CNY\",\"lastTaxFare\":861,\"serviceFee\":0,\"quantity\":1,\"ticketPrice\":0,\"serviceFeeRmb\":0,\"rmbTicketPrice\":0,\"priceType\":0,\"tax\":1020,\"bizPercentAmount\":0,\"rebatePer\":0,\"percentAmountCid\":0,\"policyId\":\"5\",\"rmbRebateAmount\":0,\"taxFirmAmount\":0,\"percentAmountHx\":0,\"ticketPriceRule\":\"0\",\"bizFirmAmount\":0,\"currencyCode\":\"HKD\",\"taxPercentAmount\":0}],\"price\":5730,\"flightSegments\":[{\"departureTime\":\"2017-09-29 08:20:00\",\"arrivalCityCode\":\" \",\"elapseTime\":240,\"departCityCode\":\" \",\"seatsRemain\":9,\"marketingCarrier\":\"CZ\",\"fromterminal\":\" \",\"stopQuantity\":\"0\",\"arrivalTime\":\"2017-09-29 12:20:00\",\"stayTime\":225,\"originDestinationOption\":\"0\",\"operatingCarrier\":\"CZ\",\"eQuipType\":\"320\",\"departureTimeZone\":\"8\",\"jingting\":\" \",\"flightNumber\":\"6301\",\"meal\":\"L\",\"departAirport\":\"SHE\",\"eTicket\":\"true\",\"arrivalTimeZone\":\"8\",\"sharecode\":false,\"marriageGrp\":\"O\",\"bookingCode\":\"B\",\"arrivalAirport\":\"CAN\",\"toterminal\":\" \"},{\"departureTime\":\"2017-09-29 16:05:00\",\"arrivalCityCode\":\" \",\"elapseTime\":170,\"departCityCode\":\" \",\"seatsRemain\":9,\"marketingCarrier\":\"CZ\",\"fromterminal\":\" \",\"stopQuantity\":\"0\",\"arrivalTime\":\"2017-09-29 17:55:00\",\"stayTime\":100,\"originDestinationOption\":\"0\",\"operatingCarrier\":\"CZ\",\"eQuipType\":\"738\",\"departureTimeZone\":\"8\",\"jingting\":\" \",\"flightNumber\":\"363\",\"meal\":\"C\",\"departAirport\":\"CAN\",\"eTicket\":\"true\",\"arrivalTimeZone\":\"7\",\"sharecode\":false,\"marriageGrp\":\"O\",\"bookingCode\":\"B\",\"arrivalAirport\":\"BKK\",\"toterminal\":\" \"},{\"departureTime\":\"2017-10-14 02:30:00\",\"arrivalCityCode\":\" \",\"elapseTime\":220,\"departCityCode\":\" \",\"seatsRemain\":9,\"marketingCarrier\":\"MU\",\"fromterminal\":\" \",\"stopQuantity\":\"0\",\"arrivalTime\":\"2017-10-14 07:10:00\",\"stayTime\":100,\"originDestinationOption\":\"1\",\"operatingCarrier\":\"MU\",\"eQuipType\":\"320\",\"departureTimeZone\":\"7\",\"jingting\":\" \",\"flightNumber\":\"548\",\"meal\":\"B\",\"departAirport\":\"BKK\",\"eTicket\":\"true\",\"arrivalTimeZone\":\"8\",\"sharecode\":false,\"marriageGrp\":\"O\",\"bookingCode\":\"S\",\"arrivalAirport\":\"PVG\",\"toterminal\":\"1\"},{\"departureTime\":\"2017-10-14 08:50:00\",\"arrivalCityCode\":\" \",\"elapseTime\":155,\"departCityCode\":\" \",\"seatsRemain\":9,\"marketingCarrier\":\"FM\",\"fromterminal\":\"1\",\"stopQuantity\":\"0\",\"arrivalTime\":\"2017-10-14 11:25:00\",\"stayTime\":0,\"originDestinationOption\":\"1\",\"operatingCarrier\":\"FM\",\"eQuipType\":\"738\",\"departureTimeZone\":\"8\",\"jingting\":\" \",\"flightNumber\":\"9367\",\"meal\":\"S\",\"departAirport\":\"PVG\",\"eTicket\":\"true\",\"arrivalTimeZone\":\"8\",\"sharecode\":false,\"marriageGrp\":\"O\",\"bookingCode\":\"B\",\"arrivalAirport\":\"SHE\",\"toterminal\":\" \"}],\"pricej\":{\"jsRatio\":1,\"adultTax\":861,\"childTax\":0,\"adultPrice\":3972,\"localCurrencyCode\":\"HKD\",\"childPrice\":0,\"priceAddInfo\":\"\",\"rmbRatio\":0.8433},\"farebasis\":\"B2PRPQB,B2PRPQB;SPRCD,SPRCD\",\"marriageGrps\":\"O,O,O,O\",\"policy\":\"<br> <br> <br>\",\"price2\":5730,\"validatingcarrier\":\"CZ\",\"flightOption\":\"roundTrip\",\"ywprice\":4710,\"faretype\":\"public,public;public,public\",\"fromto\":\"SHE-BKK\",\"ywprice2\":4710,\"infoSource\":\"public\",\"routecode\":\"SHE-CAN,CAN-BKK,BKK-PVG,PVG-SHE;CZ,CZ,MU,FM;CZ6301,CZ363,MU548,FM9367;2017-09-29 08:20:00/2017-09-29 12:20:00,2017-09-29 16:05:00/2017-09-29 17:55:00,2017-10-14 02:30:00/2017-10-14 07:10:00,2017-10-14 08:50:00/2017-10-14 11:25:00;B,B,S,B\",\"flightcode\":\"FM\",\"itineraryID\":\"25\",\"basic\":\"ABUS_F-25#25#Economy#E#0^ ^ ^CZ^CZ^6301^2017-09-29 08:20:00^2017-09-29 12:20:00^9^240^SHE^CAN^320^true^B^L^225^0^ ^false^ ^ ^8^8^O@^0^ ^ ^CZ^CZ^363^2017-09-29 16:05:00^2017-09-29 17:55:00^9^170^CAN^BKK^738^true^B^C^100^0^ ^false^ ^ ^8^7^O@^1^ ^ ^MU^MU^548^2017-10-14 02:30:00^2017-10-14 07:10:00^9^220^BKK^PVG^320^true^S^B^100^0^ ^false^ ^1^7^8^O@^1^ ^ ^FM^FM^9367^2017-10-14 08:50:00^2017-10-14 11:25:00^9^155^PVG^SHE^738^true^B^S^0^0^ ^false^1^ ^8^8^O#4710^1020^1^ADT^HKD^0^0,1-1P;2,3-2P##SHE-CAN,CAN-BKK,BKK-PVG,PVG-SHE;CZ,CZ,MU,FM;CZ6301,CZ363,MU548,FM9367;2017-09-29 08:20:00/2017-09-29 12:20:00,2017-09-29 16:05:00/2017-09-29 17:55:00,2017-10-14 02:30:00/2017-10-14 07:10:00,2017-10-14 08:50:00/2017-10-14 11:25:00;B,B,S,B#public#roundTrip#ABUS_F#SHE-BKK#FM#5730#4710#5730#4710#0#0MLD#B2PRPQB,B2PRPQB;SPRCD,SPRCD#CZ#public,public;public,public\",\"qsource\":\"0MLD\"},\"vendorId\":\"600040\",\"index\":16,\"queryResult\":{\"applyType\":\"0\",\"adultTax\":861,\"data\":\"5896426788653514_16\",\"childTax\":861,\"adultPrice\":3978,\"priceType\":\"0\",\"rule\":{\"changesInfoList\":[{\"revNoShowCondition\":0,\"changesType\":\"0\",\"passengerType\":\"0\",\"revNoshow\":\"T\",\"changesStatus\":\"T\"},{\"revNoShowCondition\":0,\"changesType\":\"1\",\"passengerType\":\"0\",\"revNoshow\":\"T\",\"changesStatus\":\"T\"}],\"formatBaggageInfoList\":[{\"cnBaggage\":\"\",\"passengerType\":\"0\",\"baggageWeight\":-1,\"enBaggage\":\"\",\"baggagePiece\":1,\"segmentNo\":1},{\"cnBaggage\":\"\",\"passengerType\":\"0\",\"baggageWeight\":-1,\"enBaggage\":\"\",\"baggagePiece\":1,\"segmentNo\":2},{\"cnBaggage\":\"\",\"passengerType\":\"0\",\"baggageWeight\":-1,\"enBaggage\":\"\",\"baggagePiece\":2,\"segmentNo\":3},{\"cnBaggage\":\"\",\"passengerType\":\"0\",\"baggageWeight\":-1,\"enBaggage\":\"\",\"baggagePiece\":2,\"segmentNo\":4}],\"refundInfoList\":[{\"refundType\":\"0\",\"passengerType\":\"0\",\"refNoshow\":\"T\",\"refNoShowCondition\":0,\"refundStatus\":\"T\"},{\"refundType\":\"1\",\"passengerType\":\"0\",\"refNoshow\":\"T\",\"refNoShowCondition\":0,\"refundStatus\":\"T\"}]},\"childTaxType\":\"0\",\"planCategory\":0,\"infantPrice\":0,\"fromSegments\":[{\"operatingFlightNo\":\"\",\"stopCities\":\" \",\"depTime\":\"201709290820\",\"cabinGrade\":\"Y\",\"cabin\":\"B\",\"depAirport\":\"SHE\",\"seatCount\":\"9\",\"flightNumber\":\"CZ6301\",\"carrier\":\"CZ\",\"codeShare\":false,\"aircraftCode\":\"320\",\"arrAirport\":\"CAN\",\"operatingCarrier\":\"CZ\",\"arrTime\":\"201709291220\"},{\"operatingFlightNo\":\"\",\"stopCities\":\" \",\"depTime\":\"201709291605\",\"cabinGrade\":\"Y\",\"cabin\":\"B\",\"depAirport\":\"CAN\",\"seatCount\":\"9\",\"flightNumber\":\"CZ363\",\"carrier\":\"CZ\",\"codeShare\":false,\"aircraftCode\":\"738\",\"arrAirport\":\"BKK\",\"operatingCarrier\":\"CZ\",\"arrTime\":\"201709291755\"}],\"nationality\":\"\",\"reservationType\":\"1B\",\"validatingCarrier\":\"CZ\",\"invoiceType\":\"F\",\"adultTaxType\":\"0\",\"childPrice\":3978,\"retSegments\":[{\"operatingFlightNo\":\"\",\"stopCities\":\" \",\"depTime\":\"201710140230\",\"cabinGrade\":\"Y\",\"cabin\":\"S\",\"depAirport\":\"BKK\",\"seatCount\":\"9\",\"flightNumber\":\"MU548\",\"carrier\":\"MU\",\"codeShare\":false,\"aircraftCode\":\"320\",\"arrAirport\":\"PVG\",\"operatingCarrier\":\"MU\",\"arrTime\":\"201710140710\"},{\"operatingFlightNo\":\"\",\"stopCities\":\" \",\"depTime\":\"201710140850\",\"cabinGrade\":\"Y\",\"cabin\":\"B\",\"depAirport\":\"PVG\",\"seatCount\":\"9\",\"flightNumber\":\"FM9367\",\"carrier\":\"FM\",\"codeShare\":false,\"aircraftCode\":\"738\",\"arrAirport\":\"SHE\",\"operatingCarrier\":\"FM\",\"arrTime\":\"201710141125\"}],\"infantTax\":0,\"productType\":\"PUB\"},\"ds\":\"ABUS_F\",\"queryCondition\":{\"childNumber\":0,\"uname\":\"admin\",\"ipccsandids\":[],\"otaName\":\"ctrip\",\"toCity\":\"BKK\",\"channel\":\"F\",\"infantNumber\":0,\"retDate\":\"20171014\",\"adultNumber\":1,\"referenceId\":\"ce20ce0c-2742-4e57-b853-80eecb26d6e8\",\"fromDate\":\"20170929\",\"ipccs\":[\"600040\"],\"tripType\":\"2\",\"guid\":\"5896426788653514\",\"pwd\":\"shijie99\",\"isFusiMillis\":false,\"fromCity\":\"SHE\",\"tradeId\":\"101\",\"searchTimeout\":5800,\"cid\":\"ctriplantianxy20170904\"},\"ipcc\":\"0MLD\",\"guid\":\"5896426788653514\",\"dsipcc\":\"ABUS_F@0MLD\",\"marriageGrps\":\"O,O,O,O\"}").append("date", new Date());    
//						collection.insertOne(doc); 
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//	
//				}
//			});
//         }    
////         向文档中插入列表    
//         
//         System.out.println("----");
         
//         collection.insertMany(documents);    
    
        /***************** 数据读取 ****************************************/    
        // // 显示集合中的文档的数量    
//         System.out.println(collection.count());    
        // 查询集合中的第一个文档    
//         Document myDoc = collection.find().first();    
//         System.out.println(myDoc.toJson());    
    
        //获取集合中的全部文档    
//         MongoCursor<Document> cursor = collection.find().iterator();    
//         try {    
//	         while (cursor.hasNext()) {    
//	        	 System.out.println(cursor.next().toJson());    
//	         }    
//         } finally {    
//        	 cursor.close();    
//         }    
    
        //获取全部文档的另一种方法    
        // for (Document cur : collection.find()) {    
        // System.out.println(cur.toJson());    
        // }    
    
        // // 根据条件获取某分文档 eq:==    
//         Document myDoc1 = collection.find(Filters.eq("i", 71)).first();    
//         System.out.println(myDoc1.toJson());    
    
        // 通过查询语句一次性获取多个数据    
//         Block<Document> printBlock = new Block<Document>() {    
//	         @Override    
//	         public void apply(final Document document) {    
//	        	 System.out.println(document.toJson());    
//	         }    
//         };    
        // 获得所有大于50的    
//         collection.find(Filters.gt("i", 50)).forEach(printBlock);    
        // 大于50 小于等于 60    
//         collection.find(Filters.and(Filters.gt("i", 50), Filters.lte("i", 60))).forEach(printBlock);    
    
//        // 对输出文档进行排序,-1为递减，1为递增    
//        // 官方文档的例子有误：http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#sorting-documents    
//         Document myDoc11 = collection.find(Filters.exists("i")).sort(new BasicDBObject("i", 1)).first();    
//         System.out.println(myDoc11.toJson());    
//    
//        // 选择性输出结果中的元素，0为不显示，1为显示    
//        // 官方文档中的例子又不能用：http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#projecting-fields    
//         BasicDBObject exclude = new BasicDBObject();    
//         exclude.append("_id", 0);    
//         exclude.append("count", 0);    
//         exclude.append("name", 1);    
//         exclude.append("info", 1);    
//         Document myDoc111 = collection.find().projection(exclude).first();    
//         System.out.println(myDoc111.toJson());    
    
        /************************* 修改数据库中数据 *************************************/    
    
        // 修改时的参数：    
        // $inc 对指定的元素加    
        // $mul 乘    
        // $rename 修改元素名称    
        // $setOnInsert 如果以前没有这个元素则增加这个元素，否则不作任何更改    
        // $set 修改制定元素的值    
        // $unset 移除特定的元素    
        // $min 如果原始数据更大则不修改，否则修改为指定的值    
        // $max 与$min相反    
        // $currentDate 修改为目前的时间    
    
        // //修改第一个符合条件的数据    
        // $set 为修改    
//         collection.updateOne(Filters.eq("i", 10), new Document("$set", new Document("i", 110)));    
        // // 获取全部文档,可以看到以前10的地方变成了110    
//         for (Document cur : collection.find()) {    
//        	 System.out.println(cur.toJson());    
//         }    
    
        // 批量修改数据并且返回修改的结果，讲所有小于100的结果都加100    
//         UpdateResult updateResult = collection.updateMany(Filters.lt("i", 100), new Document("$inc", new Document("i", 100)));    
        // // 显示发生变化的行数    
//         System.out.println(updateResult.getModifiedCount());    
        // // 获取全部文档,可以看到除了刚才修改的110其他的全为了100    
//         for (Document cur : collection.find()) {    
//        	 System.out.println(cur.toJson());    
//         }    
    
        /************************** 删除数据 *****************************/    
        // 删除第一个符合条件的数据    
//         collection.deleteOne(Filters.eq("i", 110));    
        // // 获取全部文档,可以看到没有110这个数了    
//         for (Document cur : collection.find()) {    
//        	 System.out.println(cur.toJson());    
//         }    
    
        // 删除所有符合条件的数据，并且返回结果    
//         long t = System.currentTimeMillis();
//         DeleteResult deleteResult = collection.deleteMany(Filters.lt("datetime", new Date().getTime()));    
//         // 输出删除的行数    
//         System.out.println(System.currentTimeMillis()-t);
//         System.out.println(deleteResult.getDeletedCount());    
        // // 获取全部文档,所有i>=100的数据都没了    
//         for (Document cur : collection.find()) {    
//        	 System.out.println(cur.toJson());    
//         }    
        /*************************** 程序块，一次执行多条语句 ********************************/    
        // 按照语句先后顺序执行    
//		List list = Arrays.asList(new InsertOneModel<>(new Document("_id", 4)),
//				new InsertOneModel<>(new Document("_id", 5)),
//				new InsertOneModel<>(new Document("_id", 6)),
//				new UpdateOneModel<>(new Document("_id", 1), new Document("$set", new Document("x", 2))), 
//				new DeleteOneModel<>(new Document("_id", 2)),
//				new ReplaceOneModel<>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));
//		collection.bulkWrite(list);
		// 获取全部文档
//		for (Document cur : collection.find()) {
//			System.out.println(cur.toJson());
//		}
//		list = Arrays.asList(new InsertOneModel<>(new Document("_id", 4)),
//				new InsertOneModel<>(new Document("_id", 5)),
//				new InsertOneModel<>(new Document("_id", 6)),
//				new UpdateOneModel<>(new Document("_id", 1), 
//				new Document("$set", new Document("x", 2))), 
//				new DeleteOneModel<>(new Document("_id", 2)),
//				new ReplaceOneModel<>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));
		// 不按照语句先后顺序执行
//		collection.bulkWrite(list, new BulkWriteOptions().ordered(false));
		// 获取全部文档
//		for (Document cur : collection.find()) {
//			System.out.println(cur.toJson());
//		}
            
            
        // 关闭数据库连接    
        mongoClient.close();    
	}
}
